package net.xiduth.cores;

import net.xiduth.game.player.content.exchange.ItemOffer.OfferType;
import net.xiduth.game.player.content.grandexchange.GrandExchangeOffer;
import net.xiduth.game.player.content.grandexchange.WorldOffers;

/**
 * @author Tyluur <itstyluur@gmail.com>
 * @since 2012-08-17
 */
public class GrandExchangeThread extends Thread {

	protected GrandExchangeThread() {
		setPriority(Thread.MIN_PRIORITY);
		setName("Grand Exchange Thread");
	}

	@Override
	public void run() {
		while(!CoresManager.shutdown) {
			for (GrandExchangeOffer buyOffer : WorldOffers.getOffers()) {
				switch(buyOffer.getType()) {
				case BUY:
					for (GrandExchangeOffer sellOffer : WorldOffers.getOffers()) {
						if (sellOffer.isFinished() || buyOffer.isFinished() || sellOffer.getOwner() == null || buyOffer.getOwner() == null) continue;
						StringBuilder bldr = new StringBuilder();
						bldr.append(sellOffer.getOwner().getUsername() + ", " + buyOffer.getOwner().getUsername());
						if (sellOffer == buyOffer) continue;
						if (sellOffer.getType() == OfferType.SELL) {
							if (sellOffer.getItem().getId() == buyOffer.getItem().getId()) {
								if (buyOffer.getOfferedAmount() >= sellOffer.getOfferedAmount()) {
									buyOffer.updateAmountCompleted(sellOffer.getOfferedAmount());
									sellOffer.updateAmountCompleted(sellOffer.getOfferedAmount());
									sellOffer.getOwner().getGrandExchange().updatePlayer();
									buyOffer.getOwner().getGrandExchange().updatePlayer();
								} else if (sellOffer.getOfferedAmount() >= buyOffer.getOfferedAmount()) {
									sellOffer.updateAmountCompleted(buyOffer.getOfferedAmount());
									buyOffer.updateAmountCompleted(buyOffer.getOfferedAmount());
									sellOffer.getOwner().getGrandExchange().updatePlayer();
									buyOffer.getOwner().getGrandExchange().updatePlayer();
								}
							}
						}
					}
					break;
				case SELL:
					break;
				}
			}
			try {
				Thread.sleep(20000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
